package com.yc.spring.bank.biz;

import com.yc.cinema.biz.BizException;
import com.yc.spring.bank.bean.Account;
import com.yc.spring.bank.bean.Record;
import com.yc.spring.bank.dao.AccountDao;
import com.yc.spring.bank.dao.RecordDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BankBizImpl implements BankBiz{

    @Resource
    AccountDao accountDao;   //使用接口类型定义变量

    @Resource
    RecordDao recordDao;

    @Override
    public void register(Account account) {

    }

    @Override
    @Transactional
    public void deposit(Integer id, double money) {
        //存款
        //省略参数验证
        Account account = accountDao.selectById(id);
        account.setMoney(account.getMoney() + money);
        accountDao.update(account);

        Record record = new Record();
        record.setAccountId(id);
        record.setMoney(money);


//        int i = 1/0;
        recordDao.insert(record);
    }

    @Override
    @Transactional
    public void withdraw(Integer id, double money) throws BizException {
        Account account = accountDao.selectById(id);
        if(account.getMoney() < money){
            throw new BizException("余额不足");
        }
        account.setMoney(account.getMoney() - money);
        accountDao.update(account);

        Record record = new Record();
        record.setAccountId(id);
        record.setMoney(-money);
        recordDao.insert(record);
    }

    @Override
    @Transactional(rollbackFor = BizException.class,noRollbackFor = RuntimeException.class)
    public void transfer(Integer id1, Integer id2, double money) throws BizException {
        withdraw(id1,money);

        if(money > 0){
            //编译器异常，默认不回滚
            //   noRollbackFor =  设置不会滚的运行时异常   默认情况下，运行时异常会自动回滚
//            throw new BizException("人为制造的异常！！！");
            int i = 1 / 0;
        }
        deposit(id2, money);
    }

    @Override
    public List<Record> query(Integer id) {
        return null;
    }
}
